import { BellOutlined } from '@ant-design/icons'
import { Tag } from 'antd'
import { ReactComponent as MuteIcon } from '@/desktop/assets/mute.svg'
import type { ItemBaseProps } from '@/desktop/logics/contacts'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import type { GroupContact } from '@/services/contact-types'
import ContactItemContent from './content'
import s from './group.module.less'
import { Menu, menuItems } from './menu'

export default function GroupItem(
  props: ItemBaseProps & {
    contact: GroupContact
  },
) {
  const { contact, isTop, unread } = props

  const [mutes] = useStreams(services.groups.mutes)
  const muteRecord = mutes.find(
    item => item.wxid === contact.ownerWxid && item.conversationId === contact.conversationId,
  )

  const nameExtra = <span styleName="tags">
    {contact.isExternal ? <Tag>外部群</Tag> : null}
    {contact.isOwner ? <Tag>群主</Tag> : null}
  </span>

  const renderUnread = useMemo(
    () => (muteRecord ? () => <div styleName="mute-unread"></div> : undefined),
    [muteRecord],
  )

  const muteMenuItem = useMemo(() => {
    return !muteRecord
      ? {
          icon: <span className="anticon">
            <MuteIcon style={{ width: '1em', height: '1em' }} />
          </span>,
          title: '免打扰',
          onClick: () => void services.groups.mute(contact.id),
        }
      : {
          icon: <BellOutlined />,
          title: '恢复提醒',
          onClick: () => void services.groups.cancelMute(muteRecord.id),
        }
  }, [muteRecord, contact])

  const side = <>
    {muteRecord ? <MuteIcon styleName="mute" /> : null}
    <Menu
      items={[
        muteMenuItem,
        menuItems.top(contact.id, isTop),
        menuItems.markUnread(contact.id, unread),
      ]}
    />
  </>

  return <ContactItemContent
    {...props}
    nameExtra={nameExtra}
    side={side}
    renderUnread={renderUnread}
    className={{
      current: s.current,
      name: s.name,
    }}
  />
}
